package com.tengju.user.infrastructure.persistence.redis;

import com.tengju.user.infrastructure.shared.InfraException;
import com.tengju.user.infrastructure.persistence.redis.dataobject.RedisKeyObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author wuziyang
 */
@Repository
public class SmsCodeCacheRepository{

    @Autowired
    private RedisService redisService;

    /**
     * 剩余限制时间
     */
    public Long remainLimitTime(RedisKeyObject key){

        Long expireTime = redisService.getExpireTime(key);
        if (expireTime < 0) {
            return 0L;
        }
        return expireTime;

    }

    /**
     * 校验限制时间内再次发起短信验证码获取
     */
    public boolean checkLimitTime(RedisKeyObject key, String value, long expireTime){

        return redisService.setIfAbsent(key,value,expireTime);

    }

    public boolean saveSmsCode(RedisKeyObject key, String value, long expireTime) {

        if (!(redisService.setValue(key,value,expireTime, TimeUnit.SECONDS) == 1L)) {
            throw new InfraException("保存验证码失败");
        }

        return true;

    }

    public String querySmsCode(RedisKeyObject key) {

        return redisService.getString(key);

    }

    public boolean savePwdChangeToken(RedisKeyObject key, String value, long expireTime) {
        if (!(redisService.setValue(key,value,expireTime, TimeUnit.SECONDS) == 1L)) {
            throw new InfraException("保存密码变更token失败");
        }

        return true;
    }

    public String getPwdChangeToken(RedisKeyObject key) {

        return redisService.getString(key);

    }

    public boolean delSmsCode(RedisKeyObject key) {

        return redisService.delKey(key) == 1L;

    }
}